package com.cq.smartelebicycle.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cq.smartelebicycle.R;
import com.cq.smartelebicycle.utils.WifiPswDialog;
import com.cq.smartelebicycle.utils.WifiUtils;
import com.cq.smartelebicycle.view.BluetoothListAdapter;
import com.cq.smartelebicycle.view.WifiListAdapter;
import com.cq.smartelebicycle.view.WifiListAdapter.ListItemView;

public class WifiFragment extends Fragment implements OnItemClickListener {

	public static final String TAG_ID = "WifiFragment";
	private ListView mWifilist;
	// private List<ScanResult> list; // 存放周围wifi热点对象的列表
	private List<ScanResult> wifiListString = new ArrayList<ScanResult>();
	private WifiListAdapter adapter;
	//private ArrayAdapter<String> adapter;
	private WifiUtils localWifiUtils;
	private String wifiPassword = null;
	private TextView mWifiSelected = null;
	private LinearLayout wifilayout = null;
	private boolean isScaning = false;
	private ImageView mPsw  = null;

	private ProgressDialog mDialog;
	
	private WifiStatusReceiver mWifiStatusReceiver;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View rootView = inflater.inflate(R.layout.wifi_fragment, container,
				false);
		localWifiUtils = new WifiUtils(getActivity());
		mWifilist = (ListView) rootView.findViewById(R.id.wifi_list);
		wifilayout = (LinearLayout) rootView
				.findViewById(R.id.wifi_selected_layout);
		mWifiSelected = (TextView) rootView.findViewById(R.id.wifi_selected);
		mPsw = (ImageView) rootView.findViewById(R.id.wifi_psw_select_icon);
		setSelectWifi();
		adapter = new WifiListAdapter(this,wifiListString);
		//adapter = new ArrayAdapter<String>(getActivity(),
		//android.R.layout.simple_list_item_1, wifiListString);
		if (!isScaning) {
			isScaning = true;
			new ScanWifiTask().execute();
		}
		mWifilist.setAdapter(adapter);
		mWifilist.setOnItemClickListener(this);
		return rootView;
	}

	private void setSelectWifi() {
		WifiManager wifiMgr = (WifiManager) getActivity().getSystemService(
				Context.WIFI_SERVICE);
		// int wifiState = wifiMgr.getWifiState(); String status = ""; if
		// (wifiState == WifiManager.WIFI_STATE_ENABLED) { status =
		// "WIFI_STATE_ENABLED"; }
		WifiInfo info = wifiMgr.getConnectionInfo();
		String wifiId = info != null ? info.getSSID() : null;
		Log.e("hys", "wifiId ====" + wifiId);

		if (wifiId == null) {
			wifilayout.setVisibility(View.GONE);
		} else {
			wifilayout.setVisibility(View.VISIBLE);
			mWifiSelected.setText(wifiId.replace("\"", ""));
			 int signalLevel = WifiManager.calculateSignalLevel(info.getRssi(), 5);//判断wifi强度
		      // 得到配置好的网络连接  
		        List<WifiConfiguration> wifiConfigList = wifiMgr.getConfiguredNetworks();  
		          
		        for (WifiConfiguration wifiConfiguration : wifiConfigList) {  
		            //配置过的SSID  
		            String configSSid = wifiConfiguration.SSID;  
		            configSSid = configSSid.replace("\"", "");  
		              
		            //当前连接SSID  
		            String currentSSid =info.getSSID();  
		            currentSSid = currentSSid.replace("\"", "");  
		              
		            //比较networkId，防止配置网络保存相同的SSID  
		            if (currentSSid.equals(configSSid)&&info.getNetworkId()==wifiConfiguration.networkId) {  
		            	if(getSecurity(wifiConfiguration) == SECURITY_NONE){
			                Log.e("hys", "当前网络安全性：" + getSecurity(wifiConfiguration)); 
			                mPsw.setVisibility(View.INVISIBLE);
		            	}else{
		            		mPsw.setVisibility(View.VISIBLE);
		            	}
		            }  
		        }  
			
		}
	}
    /** 
     * These values are matched in string arrays -- changes must be kept in sync 
     */  
    static final int SECURITY_NONE = 0;  
    static final int SECURITY_WEP = 1;  
    static final int SECURITY_PSK = 2;  
    static final int SECURITY_EAP = 3;  
  
    static int getSecurity(WifiConfiguration config) {  
        if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {  
            return SECURITY_PSK;  
        }  
        if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) || config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {  
            return SECURITY_EAP;  
        }  
        return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;  
    }  
	
	public static int getSecurity(ScanResult result) {  
	    if (result.capabilities.contains("WEP")) {  
	        return 1;  
	    } else if (result.capabilities.contains("PSK")) {  
	        return 2;  
	    } else if (result.capabilities.contains("EAP")) {  
	        return 3;  
	    }  
	    return 0;  
	} 


	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if (!isScaning) {
			isScaning = true;
			new ScanWifiTask().execute();
		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setMessage("正在扫描，请稍后刷新!");
			builder.setPositiveButton("OK", null);
			builder.show();
		}
		return super.onOptionsItemSelected(item);
	}


	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		menu.add(0, 0, 0, "Refresh");
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		isScaning = false;
		setHasOptionsMenu(true);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (mWifiStatusReceiver == null) {
			mWifiStatusReceiver = new WifiStatusReceiver();
		}
		IntentFilter filter = new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION);
		filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
		filter.addAction(WifiManager.RSSI_CHANGED_ACTION);
		getActivity().registerReceiver(mWifiStatusReceiver, filter);
	}


	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (mWifiStatusReceiver != null) {
			getActivity().unregisterReceiver(mWifiStatusReceiver);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		ListItemView wifi =(ListItemView) view.getTag();
		final String wifiItemSSID = wifi.wifiname.getText().toString();
		Log.e("ListOnItemClickListener", wifiItemSSID);
		WifiPswDialog pswDialog = new WifiPswDialog(getActivity(),
				new WifiPswDialog.OnCustomDialogListener() {
					@Override
					public void back(String str) {
						// TODO Auto-generated method stub
						wifiPassword = str;
						if (wifiPassword != null) {
							int netId = localWifiUtils.AddWifiConfig(
									localWifiUtils.getScanResults(),
									wifiItemSSID, wifiPassword);
							if (netId != -1) {
								localWifiUtils.getConfiguration();// 添加了配置信息，要重新得到配置信息
								localWifiUtils.ConnectWifi(netId);
							} else {
								Toast.makeText(getActivity(), "网络连接错误",
										Toast.LENGTH_SHORT).show();
							}
						}
					}
				});
		pswDialog.show();
	}

	class ScanWifiTask extends AsyncTask<Void, Void, Integer> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			if (mDialog == null) {
				mDialog = new ProgressDialog(getActivity());
				mDialog.setMessage("正在扫描...");
			}
			mDialog.show();
			super.onPreExecute();
		}

		@Override
		protected Integer doInBackground(Void... params) {
			// TODO Auto-generated method stub
			return localWifiUtils.scanWifi(wifiListString);
		}

		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result.intValue() == WifiUtils.WAIT_WIFI) {
				Toast.makeText(getActivity(), "正在打开wifi，请稍候",
						Toast.LENGTH_SHORT).show();
			} else if (result.intValue() == WifiUtils.UI_NEED_UPDATE) {
				adapter.notifyDataSetChanged();
			} else if (result.intValue() == WifiUtils.UI_NONEED_UPDATE) {
				// do nothing
			}
			isScaning = false;
			if (mDialog != null && mDialog.isShowing()) {
				mDialog.dismiss();
			}
		}
	}

	class WifiStatusReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getAction().equals(WifiManager.RSSI_CHANGED_ACTION)) {
				// signal strength changed
			} else if (intent.getAction().equals(
					WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
				// wifi连接上与否
				NetworkInfo info = intent
						.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
				if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
					//断开
				} else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {

					WifiManager wifiManager = (WifiManager) context
							.getSystemService(Context.WIFI_SERVICE);
					WifiInfo wifiInfo = wifiManager.getConnectionInfo();
					
					// 获取当前wifi名称
					//System.out.println("连接到网络 " + wifiInfo.getSSID());
					setSelectWifi();
				}

			} else if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
				// wifi打开与否
				int wifistate = intent.getIntExtra(
						WifiManager.EXTRA_WIFI_STATE,
						WifiManager.WIFI_STATE_DISABLED);

				if (wifistate == WifiManager.WIFI_STATE_DISABLED) {
					//System.out.println("系统关闭wifi");
				} else if (wifistate == WifiManager.WIFI_STATE_ENABLED) {
					//System.out.println("系统开启wifi");
				}
			}
		}
	}

}